package com.diandian.backend.jingdong.home.exchange.service;

import com.alibaba.fastjson.JSON;
import com.diandian.backend.jingdong.home.exchange.req.BatchQueryUseableInfoReq;
import com.diandian.backend.jingdong.home.exchange.req.BatchQueryUseableInfoReqData;
import com.diandian.backend.jingdong.home.exchange.resp.BusinessGetProductSkuInfoResp;
import com.diandian.jingdong.home.boot.starter.dto.WebResponseDTO;
import com.diandian.jingdong.home.boot.starter.service.stock.JingdongStockAvailableSaleBasicService;
import com.diandian.jingdong.home.boot.starter.service.stock.dto.*;
import com.diandian.jingdong.home.boot.starter.service.stock.resp.QueryOpenUseableResponseData;
import com.diandian.jingdong.home.boot.starter.service.stock.resp.QueryOpenUseableResponseDataData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class BusinessStockAvailableSaleService {

    private static final Logger logger = LoggerFactory.getLogger(BusinessStockAvailableSaleService.class);

    @Autowired
    private JingdongStockAvailableSaleBasicService stockAvailableSaleBasicService;

    @Autowired
    private BusinessDataTransferService businessDataTransferService;

    /**
     * 批量查询商品库存及可售状态信息
     * @param paramData
     * @return
     * @throws Exception
     */
    public List<BusinessGetProductSkuInfoResp> queryOpenUseable(String appKey, String appSecret, String token, String belong, BatchQueryUseableInfoReq paramData) throws Exception {

        paramData.check();
        List<BatchQueryUseableInfoReqData> dataList = paramData.getData();

        List<BusinessGetProductSkuInfoResp> result = new ArrayList<>();

        for (BatchQueryUseableInfoReqData data : dataList) {

            String offlineStoreCode = data.getOfflineStoreCode();
            String onlineStoreCode = data.getOnlineStoreCode();
            String skuCode = data.getSkuCode();

            String targetOnlineStoreCode;
            if(onlineStoreCode == null || "".equals(onlineStoreCode)){
                targetOnlineStoreCode = businessDataTransferService.offlineCodeToOnlineCode(belong, offlineStoreCode);
            } else {
                targetOnlineStoreCode = onlineStoreCode;
            }

            // 根据商家skuId获取京东skuId
            Long djSkuId = businessDataTransferService.localSkuIdToDjSkuId(appKey, appSecret, token, targetOnlineStoreCode, skuCode);
            if(djSkuId == null) {
                logger.info("批量查询商品库存及可售状态信息时商品信息缺失，参数: {}, 商家skuId：{}", JSON.toJSONString(data), skuCode);
                BusinessGetProductSkuInfoResp item = new BusinessGetProductSkuInfoResp();
                item.setOnlineStoreCode(targetOnlineStoreCode);
                item.setOfflineStoreCode(offlineStoreCode);
                item.setSkuCode(skuCode);
                item.setCurQty(null);
                item.setInQty(null);
                item.setPreQty(null);
                item.setLockQty(null);
                item.setLastModificationTime(new Date());
                item.setMessage("此商品不存在");
                result.add(item);
                continue;
            }

            // 执行同步操作
            WebResponseDTO<QueryOpenUseableResponseData> syncResponse = null;
            try{
                syncResponse = stockAvailableSaleBasicService.queryOpenUseable(appKey, appSecret, token, Arrays.asList(new QueryOpenUseableDTO(djSkuId, targetOnlineStoreCode)));
                logger.info("批量查询商品库存及可售状态信息完成,执行结果：{}", JSON.toJSONString(syncResponse));
            } catch (Exception e){
                logger.error("批量查询商品库存及可售状态信息异常", e);
            }

            // 查询异常返回
            if(syncResponse == null){
                BusinessGetProductSkuInfoResp item = new BusinessGetProductSkuInfoResp();
                item.setOnlineStoreCode(targetOnlineStoreCode);
                item.setOfflineStoreCode(offlineStoreCode);
                item.setSkuCode(skuCode);
                item.setCurQty(null);
                item.setInQty(null);
                item.setPreQty(null);
                item.setLockQty(null);
                item.setLastModificationTime(null);
                item.setMessage("查询异常");
                result.add(item);
            } else if(syncResponse.getCode() == null
                    || "".equals(syncResponse.getCode()) || !"0".equals(syncResponse.getCode()) || syncResponse.getData() == null
                    || syncResponse.getData().getRetCode() == null || "".equals(syncResponse.getData().getRetCode()) || !"0".equals(syncResponse.getData().getRetCode()) || syncResponse.getData().getData() == null || syncResponse.getData().getData().size() == 0) {
                BusinessGetProductSkuInfoResp item = new BusinessGetProductSkuInfoResp();
                item.setOnlineStoreCode(targetOnlineStoreCode);
                item.setOfflineStoreCode(offlineStoreCode);
                item.setSkuCode(skuCode);
                item.setCurQty(null);
                item.setInQty(null);
                item.setPreQty(null);
                item.setLockQty(null);
                item.setLastModificationTime(null);
                item.setMessage("未查到库存数据");
                result.add(item);
            } else {
                QueryOpenUseableResponseDataData jdStockData = syncResponse.getData().getData().get(0);
                Integer lockQty = jdStockData.getLockQty() == null ? 0 : jdStockData.getLockQty();
                Integer usableQty = jdStockData.getUsableQty() == null ? 0 : jdStockData.getUsableQty();
                Integer preQty = jdStockData.getOrderQty() == null ? 0 : jdStockData.getOrderQty();

                BusinessGetProductSkuInfoResp item = new BusinessGetProductSkuInfoResp();
                item.setOnlineStoreCode(targetOnlineStoreCode);
                item.setOfflineStoreCode(offlineStoreCode);
                item.setSkuCode(skuCode);
                item.setCurQty(usableQty.longValue());
                item.setInQty(usableQty.longValue() + preQty.longValue() + lockQty.longValue());
                item.setPreQty(preQty.longValue());
                item.setLockQty(lockQty.longValue());
                item.setLastModificationTime(new Date());
                result.add(item);
            }
        }

        return result;
    }
}
